#include<Recorder.h>
Recorder::Recorder(std::string path){
    this->path = path;
}
/*Recorder::~Recorder(){
    std::string temp = "/"+std::to_string(pid);
    sem_unlink(temp.c_str());
    temp = "/a"+std::to_string(pid);
    sem_unlink(temp.c_str());
    temp = "/b"+std::to_string(pid);
    sem_unlink(temp.c_str());
}*/
Recorder::~Recorder(){}
void Recorder::lock(int pid){
    std::string sem_name = "/"+std::to_string(pid);
    //加锁
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 1); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
    }
    sem_wait(sem); // 等待信号量(减操作)
    sem_close(sem); // 关闭信号量描述符
}
void Recorder::unlock(int pid){
    std::string sem_name = "/"+std::to_string(pid);
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 0); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
    }
    sem_post(sem); // 释放信号量(加操作)
    sem_close(sem); // 关闭信号量描述符
}
void Recorder::sem_a_up(int pid){
    std::string sem_name = "/a"+std::to_string(pid);
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 0); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
    }
    sem_post(sem); // 释放信号量(加操作)
    sem_close(sem); // 关闭信号量描述符
}
void Recorder::sem_a_down(int pid){
    std::string sem_name = "/a"+std::to_string(pid);
    //加锁
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 0); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
    }
    sem_wait(sem); // 等待信号量(减操作)
    sem_close(sem); // 关闭信号量描述符
}

void Recorder::sem_b_up(int pid){
    std::string sem_name = "/b"+std::to_string(pid);
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 1); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
    }
    sem_post(sem); // 释放信号量(加操作)
    sem_close(sem); // 关闭信号量描述符
}
void Recorder::sem_b_down(int pid){
    std::string sem_name = "/b"+std::to_string(pid);
    //加锁
    sem_t *sem = sem_open(sem_name.c_str(), O_CREAT, 0644, 1); // 打开信号量
    if (sem == SEM_FAILED) {
        perror("sem_open fail");
        return;
    }
    //std::cout<<"1"<<std::endl;

    sem_wait(sem);// 等待信号量(减操作)s
    //std::cout<<"2"<<std::endl;
    sem_close(sem); // 关闭信号量描述符

}
void Recorder::teset1(int pid){
    sem_b_down(pid);
    for(int i = 0; i <1000; i++)
    std::cout<<"1";
    std::cout<<"1\n";
    sem_a_up(pid);
        //sleep(1);

}
void Recorder::teset2(int pid){
    sem_a_down(pid);
    for(int i = 0; i <1000; i++)
    std::cout<<"2";
    std::cout<<"2\n";
    sem_b_up(pid);

}
